﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Shell;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.Windows.Resources;

namespace PostIt
{
    public class ExitException : Exception { }
    public partial class MainPage : PhoneApplicationPage
    {
        private TasksDBContext dbDataContext;
        // Constructor
        public MainPage()
        {
            dbDataContext = App.DB;
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Handle selection changed on ListBox
        private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            // Navigate to the new page
            NavigationService.Navigate(new Uri("/AddTasks.xaml", UriKind.Relative));

        }


        //Pin item
        private void Image_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //what is the itm id 
            string itemId = ((System.Windows.Controls.Image)sender).Tag.ToString();
            int id = Int32.Parse(itemId);
            var tasksDB = from Tasks s in dbDataContext.Items
                          where s.TaskId == id
                          select s
                          ;

           
            var allTask = new ObservableCollection<Tasks>(tasksDB);


            string tileParameter = "taskId=" + itemId;//Use Button.Name to mark Tile 

            //if item is enable
            if (allTask[0].isDone == false)
            {
                ShellTile aTile = FindTile("taskId=" + allTask[0].TaskId);
                
                // there is no pinned task and you want to pin
                if (aTile == null)
                {
                    //create a tile 
                    StandardTileData secondaryTile = new StandardTileData
                    {

                        Title = allTask[0].tileText,
                        BackgroundImage = new Uri("/images/tiles/" + allTask[0].backColor.Substring(1, 8) + ".png", UriKind.Relative),
                        BackBackgroundImage = new Uri("/images/tiles/" + allTask[0].backColor.Substring(1, 8) + ".png", UriKind.Relative),
                        BackContent = allTask[0].tileText,
                        BackTitle = allTask[0].CreationDate.ToShortDateString()

                    };
                    allTask[0].isPin = !allTask[0].isPin;
                    App.DB.SubmitChanges();
                    App.ViewModel.Items.Clear();
                    App.ViewModel.LoadData();
                    ShellTile.Create(new Uri("/DetailsPage.xaml?" + tileParameter, UriKind.Relative), secondaryTile); // Pass tileParameter as QueryString 


                }
                else // you want to unpin a item from home screen
                {


                    aTile.Delete();
                    allTask[0].isPin = false;
                    App.DB.SubmitChanges();
                    App.ViewModel.Items.Clear();
                    App.ViewModel.LoadData();


                }
            }

        }

        //when back button is pressed
        private void PhoneApplicationPage_BackKeyPress_1(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //if back button is presses this is to prevent when back button target wrong page
            throw new ExitException();
        }

        //taske done button
        private void doneButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string itemId = ((System.Windows.Controls.Image)sender).Tag.ToString();
            int id = Int32.Parse(itemId);
            IQueryable<Tasks> taskQuery = from Tasks t in App.DB.Items where t.TaskId == id select t;
            Tasks aTask = taskQuery.FirstOrDefault();

            aTask.isDone = !(aTask.isDone);

            App.DB.SubmitChanges();
            App.ViewModel.Items.Clear();
            App.ViewModel.LoadData();





        }
        
        //fine a tile in home screen
        private ShellTile FindTile(string partOfUri)
        {
            ShellTile shellTile = ShellTile.ActiveTiles.FirstOrDefault(
                tile => tile.NavigationUri.ToString() == "/DetailsPage.xaml?" + partOfUri);

            return shellTile;
        }
        
        //view a task details
        private void view_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //// Navigate to the new page
            string itemId = ((System.Windows.Controls.Image)sender).Tag.ToString();
            NavigationService.Navigate(new Uri("/DetailsPage.xaml?taskId=" + itemId, UriKind.Relative));

            //// Reset selected index to -1 (no selection)
            MainListBox.SelectedIndex = -1;
        }

        //delete a task
        private void deleteButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            int? returned = null;

            // show message box using gamer services 
            using (var mre = new System.Threading.ManualResetEvent(false))
            {
                string[] buttons = new string[] { "Delete", "Cancel" };

                Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox(
                    "Warning",
                    "Are you sure you want to delete the task ? ",
                    buttons,
                    1, // can choose which button has the focus
                    Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.None, // can play sounds
                    result =>
                    {
                        returned = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(result);
                        mre.Set(); // could have done it all without blocking
                    }, null);

                mre.WaitOne();
            }


            if (returned == 0)
            {
                //if  usere confirm delete

                //delete from database
                string itemId = ((System.Windows.Controls.Image)sender).Tag.ToString();
                int id = Int32.Parse(itemId);
                IQueryable<Tasks> taskQuery = from Tasks t in App.DB.Items where t.TaskId == id select t;
                Tasks aTask = taskQuery.FirstOrDefault();
                App.DB.Items.DeleteOnSubmit(aTask);
                // save changes to the database
                ShellTile aTile = FindTile("taskId=" + aTask.TaskId);

                
                //if there is tile for task delete it
                if (aTile != null)
                {
                    aTile.Delete();
                }

                //refresh viewmodel
                App.DB.SubmitChanges();
                App.ViewModel.Items.Clear();
                App.ViewModel.LoadData();
            }

        }
    }
}